package net.goutalk.glcs.common.page;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.goutalk.glcs.common.constant.GlobalConstant;
import net.goutalk.glcs.common.xss.SQLFilter;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @Author: tanyujie
 * @Date:2022/3/7 14:51
 */
public class ConventPage {
    public ConventPage() {
    }

    /**
     * 分页入参 转换为 IPage
     */
    public static <T> IPage<T> getPage(@NotNull PageInput input) {
        Page<T> page = new Page<>(input.getLimit(), input.getSize());
        String orderField = SQLFilter.sqlInject(StrUtil.toUnderlineCase(input.getField()));
        String order = SQLFilter.sqlInject(StrUtil.toUnderlineCase(input.getOrder()));

        if (StrUtil.equalsIgnoreCase(GlobalConstant.ORDER_DESC, order)) {
            page.addOrder(OrderItem.desc(orderField));
        } else {
            page.addOrder(OrderItem.asc(orderField));
        }
        return page;
    }


    /**
     * 根据查询出来得分页 转换为 pageoutput
     */
    public static <T> PageOutput<T> getPageOutput(IPage<T> page) {
        PageOutput<T> output = new PageOutput<>();
        output.setTotal(Convert.toInt(page.getTotal()));
        output.setList(page.getRecords());
        return output;
    }

    /**
     * 根据查询出来得分页 转换为 pageoutput  并且重新隐射为vo
     *
     * @param page  查出来得page
     * @param clazz vo类型
     */
    public static <T> PageOutput<T> getPageOutput(IPage<?> page, Class<T> clazz) {
        PageOutput<T> output = new PageOutput<>();
        output.setTotal(Convert.toInt(page.getTotal()));
        List<T> ts = BeanUtil.copyToList(page.getRecords(), clazz);
        output.setList(ts);
        return output;
    }

    /**
     * 分页入参 转换为 IPage
     */
    public static String getOrder(@NotNull String order) {

        String orderString = SQLFilter.sqlInject(StrUtil.toUnderlineCase(order));

        if (StrUtil.equalsIgnoreCase(GlobalConstant.ORDER_DESC, orderString)) {
            return "desc";
        } else {
            return "asc";
        }
    }
}
